import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';
import 'package:mybase/base/tool/queue/FFTask.dart';

/// 依次/循环 执行tasks任务队列
class FFTaskQueueManager {
  final bool isLoop; //是否一直循环
  List<FFTask> tasks;
  bool _isValide = true; //队列有效
  bool _didExe = false; //是否已经开始执行

  FFTaskQueueManager({
    required this.tasks,
    this.isLoop = false,
  });

  ///开始执行
  Future<void> start() async {
    if (_didExe) return;
    _didExe = true;
    if (FFEmpty.listIsEmpty(tasks)) return;

    await forExe();
    _isValide = false;
  }

  Future<void> forExe() async {
    if (_isValide == false) return;
    for (int i=0;i<tasks.length;i++) {
      if (_isValide == false) return;

      FFTask? task = globalSafeValueFromList<FFTask>(tasks, i);
      if (task == null) return;
      await task.exe();
    }

    if (_isValide == false) return;
    if (isLoop) {
      await forExe();
    }
  }

  ///手动停止
  dispose() {
    _isValide = false;
  }
}
